// 在浏览器F12控制台中运行的WebSocket测试代码
// 复制以下代码到浏览器控制台中执行

(function() {
    const wsUrl = 'ws://localhost:8000/ws/ai-chat/conversations/1/stream/?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzU3NTU2Mzc0LCJpYXQiOjE3NTc0Njk5NzQsImp0aSI6IjhkOWI4NGZjYjdmMjRhMjY5Mzk1NDZlMzhlYTZmZjA3IiwidXNlcl9pZCI6MX0.bWd1svLy4maV21C6X08I66VaH_BaBUogYtWz53HOUh0';
    
    console.log('🔗 尝试连接到:', wsUrl);
    
    const ws = new WebSocket(wsUrl);
    
    ws.onopen = function(event) {
        console.log('✅ WebSocket连接成功建立!');
        console.log('🔍 连接事件:', event);
        
        // 发送心跳测试
        console.log('🏓 发送心跳测试...');
        ws.send(JSON.stringify({
            type: 'ping',
            timestamp: Date.now()
        }));
    };
    
    ws.onmessage = function(event) {
        console.log('📥 收到消息:', event.data);
        
        try {
            const data = JSON.parse(event.data);
            console.log('📋 解析后的消息:', data);
            console.log('🎯 消息类型:', data.type);
        } catch (e) {
            console.log('❌ JSON解析失败');
        }
    };
    
    ws.onerror = function(error) {
        console.error('❌ WebSocket连接错误:', error);
        console.error('❌ 错误详情:', {
            type: error.type,
            target: error.target,
            readyState: error.target ? error.target.readyState : 'unknown'
        });
    };
    
    ws.onclose = function(event) {
        console.log('🔌 WebSocket连接已关闭');
        console.log('📊 关闭详情:', {
            code: event.code,
            reason: event.reason,
            wasClean: event.wasClean
        });
        
        // 解释关闭代码
        const closeCodeMeaning = {
            1000: '正常关闭',
            1001: '端点离开',
            1002: '协议错误',
            1003: '不支持的数据类型',
            1006: '异常关闭',
            1011: '服务器错误',
            1012: '服务重启',
            1013: '临时过载',
            1014: '网关超时'
        };
        
        console.log(`🔍 关闭代码含义: ${event.code} - ${closeCodeMeaning[event.code] || '未知错误'}`);
    };
    
    // 5秒后尝试发送流式消息测试
    setTimeout(() => {
        if (ws.readyState === WebSocket.OPEN) {
            console.log('🚀 发送流式消息测试...');
            ws.send(JSON.stringify({
                type: 'start_stream',
                message: '你好，这是一个测试消息',
                model: 'gpt-3.5-turbo',
                role: 'user'
            }));
        } else {
            console.log('❌ WebSocket未连接，无法发送消息');
        }
    }, 5000);
    
    // 10秒后关闭连接
    setTimeout(() => {
        console.log('⏰ 测试完成，关闭连接');
        ws.close();
    }, 10000);
    
    // 将WebSocket对象暴露到全局，方便调试
    window.testWs = ws;
    console.log('💡 WebSocket对象已保存到 window.testWs，可用于进一步调试');
    
    return ws;
})();
